import {type CodegenTableDTO, type CodegenColumnDTO, type TableQuery, getCommonFields} from '@/api/codegen'
import { codegenApi, datasourceApi } from '@/api/codegen'
import { ElMessage } from 'element-plus'
import type { SearchField, TableColumn, TableConfig, ApiConfig } from '@/components/base/CommonTable/types'
import type { FormField } from '@/components/base/CommonForm/types'
import type {PageQuery, PageResult} from "@/types/common";

// 自定义校验函数
const validateTableName = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入表名'))
  } else if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(value)) {
    callback(new Error('表名必须以字母开头，只能包含字母、数字和下划线'))
  } else {
    callback()
  }
}

const validateEntityName = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入实体类名'))
  } else if (!/^[A-Z][a-zA-Z0-9]*$/.test(value)) {
    callback(new Error('实体类名必须以大写字母开头，只能包含字母和数字'))
  } else {
    callback()
  }
}

const validatePackageName = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入包名'))
  } else if (!/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/.test(value)) {
    callback(new Error('包名格式不正确，如：com.example.demo'))
  } else {
    callback()
  }
}

const validatePath = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入生成路径'))
  } else if (!/^[/\\]/.test(value)) {
    callback(new Error('路径必须以 / 或 \\ 开头'))
  } else {
    callback()
  }
}

// 表单字段配置
export const getFormFields = (isEdit: boolean, datasourceOptions: any[] = []): FormField[] => [
  {
    prop: 'datasourceId',
    label: '数据源',
    type: 'select',
    required: true,
    placeholder: '请选择数据源',
    options: datasourceOptions,
    rules: [{ required: true, message: '请选择数据源', trigger: 'change' }]
  },
  {
    prop: 'tableName',
    label: '表名',
    type: 'input',
    required: true,
    placeholder: '请输入表名',
    disabled: isEdit,
    rules: [
      { required: true, message: '请输入表名', trigger: 'blur' },
      { validator: validateTableName, trigger: 'blur' }
    ]
  },
  {
    prop: 'tableComment',
    label: '表注释',
    type: 'input',
    required: true,
    placeholder: '请输入表注释',
    rules: [{ required: true, message: '请输入表注释', trigger: 'blur' }]
  },
  {
    prop: 'entityName',
    label: '实体类名',
    type: 'input',
    required: true,
    placeholder: '请输入实体类名',
    rules: [
      { required: true, message: '请输入实体类名', trigger: 'blur' },
      { validator: validateEntityName, trigger: 'blur' }
    ]
  },
  {
    prop: 'packageName',
    label: '包名',
    type: 'input',
    required: true,
    placeholder: '请输入包名，如：com.example.demo',
    rules: [
      { required: true, message: '请输入包名', trigger: 'blur' },
      { validator: validatePackageName, trigger: 'blur' }
    ]
  },
  {
    prop: 'generatePath',
    label: '生成路径',
    type: 'input',
    required: true,
    placeholder: '请输入代码生成路径',
    rules: [
      { required: true, message: '请输入生成路径', trigger: 'blur' },
      { validator: validatePath, trigger: 'blur' }
    ]
  },
  {
    prop: 'author',
    label: '作者',
    type: 'input',
    required: true,
    placeholder: '请输入作者名称',
    rules: [{ required: true, message: '请输入作者名称', trigger: 'blur' }]
  },
  {
    prop: 'columns',
    label: '字段配置',
    type: 'table',
    required: true,
    columns: [
      {
        prop: 'columnName',
        label: '字段名',
        type: 'input',
        required: true,
        width: 120
      },
      {
        prop: 'columnType',
        label: '字段类型',
        type: 'select',
        required: true,
        width: 120,
        options: [
          {label: 'VARCHAR', value: 'VARCHAR'},
          {label: 'CHAR', value: 'CHAR'},
          {label: 'TEXT', value: 'TEXT'},
          {label: 'INT', value: 'INT'},
          {label: 'BIGINT', value: 'BIGINT'},
          {label: 'DECIMAL', value: 'DECIMAL'},
          {label: 'DOUBLE', value: 'DOUBLE'},
          {label: 'FLOAT', value: 'FLOAT'},
          {label: 'DATE', value: 'DATE'},
          {label: 'DATETIME', value: 'DATETIME'},
          {label: 'TIMESTAMP', value: 'TIMESTAMP'},
          {label: 'BOOLEAN', value: 'BOOLEAN'},
          {label: 'TINYINT', value: 'TINYINT'}
        ]
      },
      {
        prop: 'columnLength',
        label: '长度',
        type: 'number',
        width: 120
      },
      {
        prop: 'columnScale',
        label: '小数位',
        type: 'number',
        width: 120
      },
      {
        prop: 'columnComment',
        label: '字段注释',
        type: 'input',
        required: true,
        width: 150
      },
      {
        prop: 'isPrimaryKey',
        label: '主键',
        type: 'switch',
        width: 80,
        activeText: '是',
        inactiveText: '否',
        activeValue: true,
        inactiveValue: false
      },
      {
        prop: 'isAutoIncrement',
        label: '自增',
        type: 'switch',
        width: 80,
        activeText: '是',
        inactiveText: '否',
        activeValue: true,
        inactiveValue: false
      },
      {
        prop: 'isNullable',
        label: '可空',
        type: 'switch',
        width: 80,
        activeText: '是',
        inactiveText: '否',
        activeValue: true,
        inactiveValue: false
      },
      {
        prop: 'defaultValue',
        label: '默认值',
        type: 'input',
        width: 100
      }
    ],
    // 使用新的按钮配置
    buttons: [
      {
        type: 'primary',
        text: '添加字段',
        icon: 'Plus',
        onClick: (tableData: Record<string, any>[], field: string) => {
          // 添加新行
          const newRow = {
            columnName: '',
            columnComment: '',
            javaType: 'String',
            javaField: '',
            isRequired: '0',
            isInsert: '1',
            isEdit: '1',
            isList: '1',
            isQuery: '0',
            queryType: 'EQ'
          }
          tableData.push(newRow)
        }
      },
      {
        type: 'default',
        text: '添加通用字段',
        icon: 'DocumentAdd',
        onClick: async (tableData: Record<string, any>[], field: string) => {
          debugger
          // 获取通用字段
          const commonFields = await getCommonFields()
          // 添加到集合
          tableData.push(...commonFields)
          console.log('添加通用字段', { field, tableData })
        }
      }
    ],
    // 操作列配置
    showOperationColumn: true,
    operationColumnLabel: '操作',
    operationColumnWidth: 100,
    // 禁用删除第一行（通常是ID字段）
    disableDeleteFirstRow: true
  }
]

// 表格列配置
export const getTableColumns = (): TableColumn[] => [
  {
    prop: 'id',
    label: 'ID',
    width: 80
  },
  {
    prop: 'tableName',
    label: '表名',
    width: 150
  },
  {
    prop: 'tableComment',
    label: '表注释',
    width: 200
  },
  {
    prop: 'entityName',
    label: '实体类名',
    width: 150
  },
  {
    prop: 'packageName',
    label: '包名',
    width: 200
  },
  {
    prop: 'author',
    label: '作者',
    width: 100
  },
  {
    prop: 'columnCount',
    label: '字段数量',
    width: 100
  },
  {
    prop: 'status',
    label: '状态',
    width: 100
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 180
  },
  {
    prop: 'updateTime',
    label: '更新时间',
    width: 180
  }
]

// 表格搜索字段配置
export const getSearchFields = (): SearchField[] => [
  {
    key: 'datasourceId',
    label: '数据源',
    type: 'select',
    placeholder: '请选择数据源',
    options: [], // 动态加载
  },
  {
    key: 'tableName',
    label: '表名',
    type: 'text',
    placeholder: '请输入表名',
  },
  {
    key: 'entityName',
    label: '实体类名',
    type: 'text',
    placeholder: '请输入实体类名',
  },
  {
    key: 'author',
    label: '作者',
    type: 'text',
    placeholder: '请输入作者',
  },
  {
    key: 'createTime',
    label: '创建时间',
    type: 'date',
    placeholder: '请选择创建时间',
  }
]

// 表格配置
export const getTableConfig = (): TableConfig => ({
  title: '表管理',
  description: '管理数据库表配置，支持代码生成和表结构同步',
  showHeader: true,
  showAddButton: true,
  addButtonText: '新建表',
  showSearch: true,
  showPagination: true,
  showSelection: true,
  showIndex: true,
  showActions: true,
  border: true,
  stripe: true,
  size: 'default',
  height: 'auto',
  searchFields: getSearchFields(),
  batchActions: [
    {
      text: '批量删除',
      type: 'danger',
      icon: 'Delete',
      handler: 'batchDelete'
    },
    {
      text: '批量生成代码',
      type: 'primary',
      icon: 'Document',
      handler: 'batchGenerateCode'
    },
    {
      text: '批量创建表',
      type: 'success',
      icon: 'Plus',
      handler: 'batchCreateTable'
    }
  ]
})

// API配置
export const getApiConfig = (): ApiConfig => ({
// 分页请求数据处理
  listApi: async (pageQuery: PageQuery<TableQuery>): Promise<PageResult<CodegenTableDTO>> => {
    const data =  await codegenApi.pageTableConfigs(pageQuery);
    // 将 data 内的数据进行转换
    data.records.forEach((item: CodegenTableDTO)=>{
      // 将columnsConfig转会数据对象
      item.columns = JSON.parse(item.columnsConfig)
    })
    return data
  },
  deleteApi: codegenApi.deleteTableConfig
})

// 业务操作API
export const TableApis = {
  // 创建表配置
  createTableConfig: async (data: CodegenTableDTO) => {
    try {
      const result = await codegenApi.saveTableConfig(data)
      return result
    } catch (error: any) {
      ElMessage.error(error.message || '创建表配置失败')
      throw error
    }
  },

  // 更新表配置
  updateTableConfig: async (data: CodegenTableDTO) => {
    try {
      const result = await codegenApi.updateTableConfig(data.id as string, data)
      return result
    } catch (error: any) {
      ElMessage.error(error.message || '更新表配置失败')
      throw error
    }
  },

  // 删除表配置
  deleteTableConfig: async (id: string | number) => {
    try {
      const result = await codegenApi.deleteTableConfig(String(id))
      return result
    } catch (error: any) {
      ElMessage.error(error.message || '删除表配置失败')
      throw error
    }
  },

  // 同步表结构
  syncTableStructure: async (datasourceId: string | number, tableId: string | number) => {
    try {
      const result = await codegenApi.syncTableStructure(String(datasourceId), String(tableId))
      ElMessage.success('表结构同步成功')
      return result
    } catch (error: any) {
      ElMessage.error(error.message || '表结构同步失败')
      throw error
    }
  },

  // 测试表连接
  testTableConnection: async (datasourceData: any) => {
    try {
      const result = await datasourceApi.testConnection(datasourceData)
      if (result) {
        ElMessage.success('连接测试成功')
      }
      return result
    } catch (error: any) {
      ElMessage.error(error.message || '连接测试失败')
      throw error
    }
  },

  // 批量生成代码
  batchGenerateCode: async (tables: CodegenTableDTO[]) => {
    try {
      const promises = tables.map(table => codegenApi.generateCode(table))
      const results = await Promise.all(promises)
      ElMessage.success('批量生成代码成功')
      return results
    } catch (error: any) {
      ElMessage.error(error.message || '批量生成代码失败')
      throw error
    }
  },

  // 批量创建表
  batchCreateTable: async (tables: CodegenTableDTO[]) => {
    try {
      const promises = tables.map(table => codegenApi.createTable(table))
      const results = await Promise.all(promises)
      ElMessage.success('批量创建表成功')
      return results
    } catch (error: any) {
      ElMessage.error(error.message || '批量创建表失败')
      throw error
    }
  }
}